package com.iflytek.uoamp.agent.monitor.find;

import java.util.Map;

import com.iflytek.uoamp.agent.common.constants.CommonConstants;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.log4j.Logger;

import com.iflytek.uoamp.agent.common.util.ReadFile;
import com.iflytek.uoamp.agent.core.sender.monitorsender.requestObj.GetAgentVersion;
import com.iflytek.uoamp.agent.monitor.mcagent.AgentUpdateThread;
import com.iflytek.uoamp.agent.monitor.mcagent.MCAgentMain;

/**
 * <code>执行Agent版本更新及下载任务</code>
 * <code>1.检查本地agent版本[读取conf/version文件下的版本信息]</code>
 * <code>2.获取服务器上agent的版本信息；若版本不一致则执行下载线程，下载新的agent版本</code>
 * @author zhuwei
 * @date 2016/11/18 16:35
 */
public class GetAgentVersionTask implements Runnable{

	@Override
	public void run() {
		GetAgentVersion getVersion = new GetAgentVersion();
		// 捕获异常，更新线程退出
		try {
			//1.获取本地保存的agent版本信息
			String localVersion = ReadFile.readAll(CommonConstants.VERSION_PATH, "utf-8");
			
			//2.获取服务器最新的agent版本信息
			@SuppressWarnings("unchecked")
			Map<String,String> result = (Map<String, String>) MCAgentMain.getSenderClient().sendBySafe(getVersion);
			
			//3.对比本地和服务器的agent版本信息，若不相同则下载最新的agent
			if(result != null && result.entrySet().size() > 0 && !result.containsKey(localVersion)){
				Logger.getRootLogger().info("Check agent update begin.");
				// 启动agent更新线程
				new AgentUpdateThread(result,localVersion).run();
//				AgentUpdateThread agentUpdateThread = new AgentUpdateThread(result,localVersion);
//				agentUpdateThread.start();
				Logger.getRootLogger().info("Check agent update begin.");
			}
		} catch (Exception e) {
			Logger.getRootLogger().error("GetAgentVersionTask run exception, throw " + ExceptionUtils.getMessage(e));
		}
	}

}
